package com.chookss.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.StaticClass;
import com.chookss.tools.AppUtil;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RetrievePasswordActivity extends BaseAct {
    @BindView(R.id.edCompany)
    EditText edCompany;
    @BindView(R.id.edPhone)
    EditText edPhone;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.tvInit)
    TextView tvInit;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.llCompany)
    LinearLayout llCompany;
    private boolean isSure = false;//默认没有同意协议
    boolean isAdd = false; //是否是添加账号

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_password);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        isAdd = getIntent().getBooleanExtra("isAdd", false);
        if (getPackageName().equals("com.zhaofengnum")) {
            edCompany.setText(getResources().getString(R.string.app_name));
            llCompany.setVisibility(View.GONE);
        }
        ivChoice.setBackgroundResource(R.drawable.icon_no_choice_48);
        tvInit.setText("已阅读并同意");
        SpannableString spStr = new SpannableString("《用户协议》和《隐私政策》");
        String s1 = "《用户协议》";
        String s2 = "《隐私政策》";
        ClickableSpan clickSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(RetrievePasswordActivity.this,
                        WebCommonActivity.class);
                intent.putExtra("title", "用户协议");
                if(getPackageName().equals("com.zhaofengnum")){
                    intent.putExtra("url", "http://dev.zhongyuanliantuo.com:38012/zhaofeng_license.html");
                }else{
                    intent.putExtra("url", Urls.license);
                }
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(getResources().getColor(R.color.main_color));
            }
        };
        ClickableSpan clickSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(RetrievePasswordActivity.this,
                        WebCommonActivity.class);
                intent.putExtra("title", "隐私政策");
                if(getPackageName().equals("com.zhaofengnum")){
                    intent.putExtra("url", "file:///android_asset/zhaofeng_privacy.html");
                }else{
                    intent.putExtra("url", "file:///android_asset/chookss_privacy.html");
                }
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(getResources().getColor(R.color.main_color));
            }
        };
        spStr.setSpan(clickSpan, 0, s1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spStr.setSpan(clickSpan2, spStr.length() - s2.length(), spStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvInit.append(spStr);
        tvInit.setMovementMethod(LinkMovementMethod.getInstance());
        tvInit.setLongClickable(false);
        if (!isAdd) {
            //添加账号的情况下默认不显示组织名称和手机号
            String oldCompany = new ShareUtils().getString(RetrievePasswordActivity.this, StaticClass.OLD_LOGIN_COMPANYNAME, "");
            String oldPhone = new ShareUtils().getString(RetrievePasswordActivity.this, StaticClass.OLD_LOGIN_USERNAME, "");
            if (!Utils.isNull(oldCompany)) {
                edCompany.setText(oldCompany);
            }
            if (!Utils.isNull(oldPhone)) {
                edPhone.setText(oldPhone);
            }
        }
    }

    private void login() {

        if (Utils.isNull(edCompany.getText().toString().replace(" ", ""))) {
            MyToast.show("组织名称不能为空");
            return;
        }
        if (Utils.isNull(edPhone.getText().toString())) {
            MyToast.show("手机号不能为空");
            return;
        }
        if (edPhone.getText().toString().length() < 11) {
            MyToast.show("手机号位数不对");
            return;
        }
        if (!AppUtil.validatePhoneNumber(edPhone.getText().toString())) {
            MyToast.show("手机号格式不正确");
            return;
        }
        passData();
    }

    private int COUNT_TIME = 60;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if (--COUNT_TIME == 0) {
                    if (tvSure != null) {
                        tvSure.setEnabled(true);
                        tvSure.setClickable(true);
                        tvSure.setText("确定");
                        COUNT_TIME = 60;
                        removeMessages(0);
                    }
                } else {
                    if (tvSure != null) {
                        tvSure.setText((COUNT_TIME) + "s后重试");
                        sendEmptyMessageDelayed(0, 1000);
                    }
                }
            }
        }
    };

    private void passData() {
        tvSure.setEnabled(false);
        tvSure.setClickable(false);
        mHandler.sendEmptyMessageDelayed(0, 1000);
        Map<String, String> map = new HashMap<>();
        map.put("account", edPhone.getText().toString());
        map.put("companyName", edCompany.getText().toString());
        //登录01 单纯获取02  面试03
        map.put("smsType", "02");
        MyHttpRequest.postRequest(Urls.saveSmsCode, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    if (edCompany == null) {
                        return;
                    }
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show(jsonObject.getString("msg"));
                        new ShareUtils().putBoolean(RetrievePasswordActivity.this, StaticClass.ISLOGIN, true);
                        Intent intent = new Intent(RetrievePasswordActivity.this, AuthCodeAcquireActivity.class);
                        intent.putExtra("name", edCompany.getText().toString());
                        intent.putExtra("phone", edPhone.getText().toString());
                        startActivity(intent);
                        finish();
                    } else {
                        tvSure.setEnabled(true);
                        tvSure.setClickable(true);
                        tvSure.setText("确定");
                        COUNT_TIME = 60;
                        mHandler.removeMessages(0);
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("验证码发送失败，请重新获取");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (edPhone != null) {
            Utils.hideInputKeyboard(this, edPhone);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @OnClick({R.id.layoutTop, R.id.ivChoice, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layoutTop:
                finish();
                break;
            case R.id.ivChoice:
                if (ivChoice == null) {
                    return;
                }
                if (isSure) {
                    isSure = false;
                    ivChoice.setBackgroundResource(R.drawable.icon_no_choice_48);
                } else {
                    isSure = true;
                    ivChoice.setBackgroundResource(R.drawable.icon_choice_48);
                }
                break;
            case R.id.tvSure:
                if (isSure) {
                    login();
                } else {
                    MyToast.show("请阅读并同意用户协议和隐私政策");
                }
                break;
        }
    }
}
